package com.dd.cloud.user.service.product.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dd.cloud.common.enums.ZkExceptionEnum;
import com.dd.cloud.common.exception.ZekeException;
import com.dd.cloud.common.interceptor.UserInterceptor;
import com.dd.cloud.common.utils.Assert;
import com.dd.cloud.common.vo.LoginInfo;
import com.dd.cloud.user.entity.doctor.DoctorUser;
import com.dd.cloud.user.entity.product.Product;
import com.dd.cloud.user.entity.product.ProductBuyRecord;
import com.dd.cloud.user.mapper.product.ProductMapper;
import com.dd.cloud.user.req.order.CreateOrderReq;
import com.dd.cloud.user.req.product.ProductPayReq;
import com.dd.cloud.user.req.product.ProductSystemPageReq;
import com.dd.cloud.user.req.product.ProductSystemUpdateReq;
import com.dd.cloud.user.res.doctor.DoctorEquityDetailRes;
import com.dd.cloud.user.res.order.PayOrderResponse;
import com.dd.cloud.user.res.product.ProductDoctorListRes;
import com.dd.cloud.user.res.product.ProductSystemPageRes;
import com.dd.cloud.user.service.doctor.IDoctorEquityService;
import com.dd.cloud.user.service.doctor.IDoctorUserService;
import com.dd.cloud.user.service.order.IOrderPayService;
import com.dd.cloud.user.service.product.IProductBuyRecordService;
import com.dd.cloud.user.service.product.IProductService;
import com.zk.pay.constants.CS;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 收费服务产品表 服务类
 *
 * @author Lx
 * @version 1.0
 * @date 2024/1/23
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements IProductService {
    @Autowired
    private IDoctorEquityService doctorEquityService;
    @Autowired
    private IOrderPayService orderPayService;
    @Autowired
    private IDoctorUserService doctorUserService;
    @Autowired
    private IProductBuyRecordService productBuyRecordService;

    /**
     * 查询收费服务产品(会员付费设置模块)
     *
     * @param req
     * @return
     */
    @Override
    public IPage<ProductSystemPageRes> queryProductSystemPage(ProductSystemPageReq req) {
        Assert.verifyStatusIdsParam(req.getClass(), req);
        IPage<ProductSystemPageRes> iPage = req.pagePojo();
        iPage = getBaseMapper().queryProductSystemPage(iPage, req);
        return iPage;
    }

    /**
     * 批量修改收费服务产品
     *
     * @param reqs
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateBatchProductSystem(List<ProductSystemUpdateReq> reqs) {
        LoginInfo loginInfo = UserInterceptor.getLoginUserInfo(LoginInfo.UserType.ADMIN).get();
        List<Product> list = new ArrayList<>(reqs.size());
        for (ProductSystemUpdateReq item : reqs) {
            Product product = new Product();
            BeanUtils.copyProperties(item, product);
            product.setUpdateId(loginInfo.getId());
            product.setUpdateType(loginInfo.getType());
            product.setUpdateDate(LocalDateTime.now());
            list.add(product);
        }
        boolean flag = updateBatchById(list);
        if (!flag) {
            throw new ZekeException(ZkExceptionEnum.UPDATE_ERROR);
        }
    }

    /**
     * 医生用户查询可购买产品服务列表
     *
     * @return
     */
    @Override
    public List<ProductDoctorListRes> queryProductDoctorList() {
        DoctorEquityDetailRes equityDetail = doctorEquityService.queryDoctorEquityDetail();
        if (equityDetail.getAccountType() == 1) {
            List<ProductDoctorListRes> listRes = getBaseMapper().queryProductDoctorList("1,11");
            if (equityDetail.getFirstMonth() != null && equityDetail.getFirstMonth() == 1) {
                for (int i = 0; i < listRes.size(); i++) {
                    if (listRes.get(i).getType() == 1 && listRes.get(i).getTypeNum() == 1 && listRes.get(i).getPower() == 1) {
                        listRes.remove(i);
                        break;
                    }
                }
            } else {
                for (int i = 0; i < listRes.size(); i++) {
                    if (listRes.get(i).getType() == 1 && listRes.get(i).getTypeNum() == 1 && listRes.get(i).getPower() == 11) {
                        listRes.remove(i);
                        break;
                    }
                }
            }
            return listRes;
        } else {
            if (equityDetail.getExpirDate() != null && equityDetail.getExpirDate().isAfter(LocalDateTime.now())) {
                return new ArrayList<>();
            }
            return getBaseMapper().queryProductDoctorList("2");
        }
    }

    /**
     * 购买产品服务
     *
     * @param request
     * @param req
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public PayOrderResponse<?> productPay(HttpServletRequest request, ProductPayReq req) {
        LoginInfo loginInfo = UserInterceptor.getLoginUserInfo(LoginInfo.UserType.DOCTOR).get();
        DoctorEquityDetailRes equityDetail = doctorEquityService.queryDoctorEquityDetail();
        Product product = getById(req.getProductId());
        if (!product.getDiscountPrice().equals(req.getPrice())) {
            throw new ZekeException(400, "价格错误");
        }
        if (product.getPower() == 1 && product.getTypeNum() == 1) {
            if (equityDetail.getAccountType() != 1) {
                throw new ZekeException(400, "慈善账号没有优惠产品服务购买");
            }
            equityDetail.setFirstMonth(equityDetail.getFirstMonth() == null ? 0 : equityDetail.getFirstMonth());
            if (equityDetail.getFirstMonth() == 1) {
                throw new ZekeException(400, "已享受首月优惠");
            }
        }
        if (product.getPower() == 2) {
            if (equityDetail.getExpirDate() != null && equityDetail.getExpirDate().isAfter(LocalDateTime.now())) {
                throw new ZekeException(400, "慈善账号服务在有效期内不可多次购买");
            }
        }
        DoctorUser doctorUser = doctorUserService.getById(loginInfo.getId());
        ProductBuyRecord productBuyRecord = new ProductBuyRecord();
        productBuyRecord.setProductId(product.getId());
        productBuyRecord.setMonth(product.getTypeNum());
        if (product.getPower() == 1 && product.getTypeNum() == 1) {
            productBuyRecord.setSpType(1);
        } else if (product.getTypeNum() == 1) {
            productBuyRecord.setSpType(2);
        } else if (product.getTypeNum() == 3) {
            productBuyRecord.setSpType(3);
        } else if (product.getTypeNum() == 12) {
            productBuyRecord.setSpType(4);
        }
        productBuyRecord.setDoctorId(loginInfo.getId());
        productBuyRecord.setDoctorName(loginInfo.getName());
        productBuyRecord.setDoctorAccount(doctorUser.getMobileNumber());
        productBuyRecord.setIsAuth(doctorUser.getIsCertification());
        productBuyRecord.setAccountType(equityDetail.getAccountType() == 1 ? 1 : 2);
        productBuyRecord.setPrice(product.getPrice());
        productBuyRecord.setActualPay(product.getDiscountPrice());
        productBuyRecord.setStatus(2);
        productBuyRecord.setCreateDate(LocalDateTime.now());
        productBuyRecordService.save(productBuyRecord);

        /*
         * 创建支付订单
         */
        CreateOrderReq orderReq = new CreateOrderReq();
        orderReq.setPayType(req.getPayType());
        orderReq.setPrice(product.getDiscountPrice());
        orderReq.setServerNo(String.valueOf(productBuyRecord.getId()));
        orderReq.setPartyId(0);
        orderReq.setPartyType(0);
        orderReq.setApply(req.getApply());
        orderReq.setProduct(CS.NOTICE_CHANNEL.MONTH);
        // 5 为生成产品服务订单号编码类型
        return orderPayService.createOrder(request, orderReq, 6);
    }
}
